package seatiger.tomcat.catalina.connector.http;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.Option;
import java.io.IOException;
import java.util.Optional;

/**
 * http响应对象
 */
@Deprecated
final public class HttpResponseImpl extends HttpResponseImpl_middle{

    private HttpResponseStream responseStream;

    @Override
    public ServletOutputStream createOutputStream() throws IOException {
        responseStream = new HttpResponseStream(this);
        return responseStream;
    }

    @Override
    public void finishResponse() throws IOException {
        if (getStatus() < HttpServletResponse.SC_BAD_REQUEST){
            if (!isStreamInitialized() && getContentLength() == -1
                    && getStatus() >= 200
                    && getStatus() != SC_NOT_MODIFIED
                    && getStatus() != SC_NO_CONTENT){
                setContentLength(0);
            }
        }else {
            setHeader("Connection", "close");
        }
        super.finishResponse();
    }

    public boolean isStreamInitialized() {
        return responseStream != null;
    }

    @Override
    public void sendError(int status, String message) throws IOException {
        addHeader("Connection", "close");
        super.sendError(status, message);
    }

    /**
     * 设置返回状态码
     * @param status
     */
    @Override
    public void setStatus(int status) {
        super.setStatus(status);
        Optional.ofNullable(responseStream)
                .ifPresent(value -> value.checkChunking(this));
    }
}
